import React, { useEffect, useState } from 'react'
import {
  Table, Button, Modal, Transfer, Popconfirm, Select,
} from 'antd'
import type { ColumnsType, TableRowSelection } from 'antd/es/table/interface'
import type { TransferItem, TransferProps } from 'antd/es/transfer'
import difference from 'lodash/difference'
import _ from 'lodash'
import './index.less'
import { paramOperatorArr } from '../../../../../utils/constans'

const { Option } = Select

interface DataType {
  id: any;
  paramName: string;
  paramDataType: string;
  paramOperator: number;
}

interface TableTransferProps extends TransferProps<TransferItem> {
  dataSource: DataType[];
  leftColumns: ColumnsType<DataType>;
  rightColumns: ColumnsType<DataType>;
}

// Customize Table Transfer
const TableTransfer = ({ leftColumns, rightColumns, ...restProps }: TableTransferProps) => (
  <Transfer {...restProps}>
    {({
        direction,
        filteredItems,
        onItemSelectAll,
        onItemSelect,
        selectedKeys: listSelectedKeys,
      }) => {
      const columns = direction === 'left' ? leftColumns : rightColumns

      const rowSelection: TableRowSelection<TransferItem> = {
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .map(({ id }) => id)
          const diffKeys = selected
            ? difference(treeSelectedKeys, listSelectedKeys)
            : difference(listSelectedKeys, treeSelectedKeys)
          onItemSelectAll(diffKeys, selected)
        },
        onSelect({ id }, selected) {
          onItemSelect(id, selected)
        },
        selectedRowKeys: listSelectedKeys,
        selections: [{
          key: 'NULL',
          text: '选中操作符为空',
          onSelect: () => {
            onItemSelectAll(filteredItems.filter(item => !item.paramOperator && item.paramOperator !== 0).map(item => item.id), true)
          },
        }, ...paramOperatorArr.map((__paramOperator, __paramOperatorIndex) => ({
          key: __paramOperator,
          text: `选中 ${__paramOperator}`,
          onSelect: () => {
            onItemSelectAll(filteredItems.filter(item => item.paramOperator === __paramOperatorIndex).map(item => item.id), true)
          },
        }))],
      }

      return (
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={filteredItems}
          size="small"
          pagination={false}
          rowKey="id"
          scroll={{ y: 'auto' }}
          onRow={({ id }) => ({
            onClick: () => {
              onItemSelect(id, !listSelectedKeys.includes(id))
            },
          })}
        />
      )
    }}
  </Transfer>
)

const ParamsTransferModal: React.FC = (props: any) => {
  const [readyData, setReadyData] = useState([])
  const [targetKeys, setTargetKeys] = useState([])
  const [selectedKeys, setSelectedKeys] = useState<string[]>([])
  const [theParamOperator, setTheParamOperator] = useState(null)
  const {
    visible, data, okFn, closeFn,
  } = props

  useEffect(() => {
    if (!visible) {
      setReadyData([])
      resetAll()
      return
    }
    setReadyData([...(_.cloneDeep(data))])
  }, [data, visible])

  const tableColumns: ColumnsType<DataType> = [
    {
      dataIndex: 'paramName',
      title: '参数名称',
    },
    {
      dataIndex: 'paramDataType',
      title: '参数类型',
    },
    {
      dataIndex: 'paramOperator',
      title: '操作符',
      render: (text, record) => <Select
        style={{ width: '64px' }}
        placeholder="全部"
        value={text}
        onChange={(e) => {
          const newData = _.cloneDeep(readyData)
          setReadyData(newData.map((x) => {
            if (x.id !== record.id) {
              return x
            }
            x.paramOperator = e
            return x
          }))
        }}
      >
        {paramOperatorArr.map((val, keyParamIndex) => (
          <Option key={`paramOperatorArr${keyParamIndex}`} value={keyParamIndex}>
            {val}
          </Option>
        ))}
      </Select>,
    },
  ]

  const onChange = (nextTargetKeys: string[]) => {
    setTargetKeys(nextTargetKeys)
  }
  const resetAll = () => {
    setTargetKeys([])
    setReadyData([...(_.cloneDeep(data))])
    setSelectedKeys([])
    setTheParamOperator(null)
    const antTransfer: any = document.querySelector('.ant-transfer.ant-transfer-customize-list')
    if (!antTransfer) return
    antTransfer.querySelectorAll('.ant-input-clear-icon')?.forEach((closeCircle: any) => {
      closeCircle && closeCircle.click()
    })
  }
  const onSelectChange = (sourceSelectedKeys: string[], targetSelectedKeys: string[]) => {
    setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys])
  }
  const renderFooter: any = (__: any, { direction }: { direction: any }) => {
    if (direction === 'left') {
      return <Popconfirm
        title="确认将操作符数据还原？"
        onConfirm={resetAll}
        okText="确认重置"
        cancelText="取消"
      >
        <Button size="small" style={{ float: 'left', margin: 5 }}>
          还原所有变更
        </Button>
      </Popconfirm>
    }
    return (
      <>
        <Button
          size="small"
          disabled={!theParamOperator && theParamOperator !== 0 || targetKeys.length === 0}
          type="primary"
          ghost
          style={{ float: 'right', margin: 5 }}
          onClick={() => {
            const newData = _.cloneDeep(readyData)
            setReadyData(newData.map((x) => {
              if (!targetKeys.includes(x.id)) {
                return x
              }
              x.paramOperator = theParamOperator
              return x
            }))
          }}
        >
          修改
        </Button>
        <div style={{ float: 'right', margin: 5 }}>
          <span>批量修改：</span>
          <Select
            placeholder="请选择"
            size="small"
            style={{ width: '64px' }}
            value={theParamOperator}
            allowClear
            onChange={(e) => {
              setTheParamOperator(e)
            }}
          >
            {paramOperatorArr.map((val, keyParamIndex) => (
              <Option key={`paramOperatorArr${keyParamIndex}`} value={keyParamIndex}>
                {val}
              </Option>
            ))}
          </Select>
        </div>
      </>
    )
  }
  return (
    <Modal
      title="操作符设置"
      className="table-transfer-modal"
      width={720}
      visible={visible}
      onOk={() => {
        okFn(readyData)
      }}
      onCancel={closeFn}
    >
      <TableTransfer
        dataSource={readyData}
        targetKeys={targetKeys}
        selectedKeys={selectedKeys}
        showSearch
        showSelectAll={false}
        onSelectChange={onSelectChange}
        onChange={onChange}
        filterOption={(inputValue, item) => item.paramName?.indexOf(inputValue) !== -1}
        leftColumns={tableColumns}
        rowKey={record => record.id}
        rightColumns={tableColumns}
        footer={renderFooter}
      />
    </Modal>
  )
}

export default ParamsTransferModal
